<template>
  <div class="message-manage">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="消息类型">
          <el-select v-model="searchForm.type" placeholder="请选择消息类型" clearable>
            <el-option label="系统通知" value="system" />
            <el-option label="业务通知" value="business" />
            <el-option label="活动通知" value="activity" />
            <el-option label="安全通知" value="security" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="未读" value="unread" />
            <el-option label="已读" value="read" />
            <el-option label="已删除" value="deleted" />
          </el-select>
        </el-form-item>
        <el-form-item label="发送时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleSend" v-permission="'system:message:send'">
        <el-icon><Message /></el-icon>发送消息
      </el-button>
      <el-button type="success" @click="handleTemplate" v-permission="'system:message:template'">
        <el-icon><Document /></el-icon>消息模板
      </el-button>
      <el-button type="danger" :disabled="!selectedMessages.length" @click="handleBatchDelete" v-permission="'system:message:delete'">
        <el-icon><Delete /></el-icon>批量删除
      </el-button>
    </div>

    <!-- 消息列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="messageList"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="消息标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="消息类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getMessageTypeTag(row.type)">
              {{ getMessageTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sender" label="发送人" width="120" />
        <el-table-column prop="receiver" label="接收人" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getMessageStatusTag(row.status)">
              {{ getMessageStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sendTime" label="发送时间" min-width="180" />
        <el-table-column prop="readTime" label="阅读时间" min-width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)" v-permission="'system:message:view'">
              查看
            </el-button>
            <el-button type="primary" link @click="handleResend(row)" v-if="row.status === 'failed'" v-permission="'system:message:send'">
              重发
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)" v-permission="'system:message:delete'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 发送消息对话框 -->
    <el-dialog
      v-model="sendDialogVisible"
      title="发送消息"
      width="700px"
    >
      <el-form
        ref="sendFormRef"
        :model="sendForm"
        :rules="sendRules"
        label-width="100px"
      >
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="sendForm.type" placeholder="请选择消息类型">
            <el-option label="系统通知" value="system" />
            <el-option label="业务通知" value="business" />
            <el-option label="活动通知" value="activity" />
            <el-option label="安全通知" value="security" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="sendForm.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="sendForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入消息内容"
          />
        </el-form-item>
        <el-form-item label="接收人" prop="receivers">
          <el-select
            v-model="sendForm.receivers"
            multiple
            filterable
            remote
            :remote-method="handleSearchUsers"
            :loading="userSearchLoading"
            placeholder="请选择接收人"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.nickname"
              :value="user.id"
            >
              <span>{{ user.nickname }}</span>
              <span class="user-info">{{ user.username }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送方式" prop="methods">
          <el-checkbox-group v-model="sendForm.methods">
            <el-checkbox label="system">系统消息</el-checkbox>
            <el-checkbox label="email">邮件</el-checkbox>
            <el-checkbox label="sms">短信</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime">
          <el-radio-group v-model="sendForm.sendTimeType">
            <el-radio label="now">立即发送</el-radio>
            <el-radio label="schedule">定时发送</el-radio>
          </el-radio-group>
          <el-date-picker
            v-if="sendForm.sendTimeType === 'schedule'"
            v-model="sendForm.scheduleTime"
            type="datetime"
            placeholder="请选择发送时间"
            style="margin-left: 10px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="sendDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSendSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 消息模板对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="消息模板"
      width="800px"
    >
      <div class="template-header">
        <el-button type="primary" @click="handleAddTemplate">
          <el-icon><Plus /></el-icon>新增模板
        </el-button>
      </div>
      <el-table :data="templateList" border style="width: 100%">
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column prop="type" label="消息类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getMessageTypeTag(row.type)">
              {{ getMessageTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题模板" min-width="200" show-overflow-tooltip />
        <el-table-column prop="content" label="内容模板" min-width="300" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEditTemplate(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDeleteTemplate(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 查看消息对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="消息详情"
      width="600px"
    >
      <div class="message-detail">
        <div class="message-header">
          <h3>{{ currentMessage.title }}</h3>
          <div class="message-meta">
            <el-tag :type="getMessageTypeTag(currentMessage.type)" size="small">
              {{ getMessageTypeLabel(currentMessage.type) }}
            </el-tag>
            <span class="sender">发送人：{{ currentMessage.sender }}</span>
            <span class="time">发送时间：{{ currentMessage.sendTime }}</span>
          </div>
        </div>
        <div class="message-content">
          {{ currentMessage.content }}
        </div>
        <div class="message-footer">
          <div class="receiver-info">
            <p>接收人：{{ currentMessage.receiver }}</p>
            <p>阅读状态：{{ getMessageStatusLabel(currentMessage.status) }}</p>
            <p v-if="currentMessage.readTime">阅读时间：{{ currentMessage.readTime }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Message, Document, Delete, Plus } from '@element-plus/icons-vue'
import {
  getMessageList,
  sendMessage,
  resendMessage,
  deleteMessage,
  batchDeleteMessages,
  getMessageTemplateList,
  createMessageTemplate,
  updateMessageTemplate,
  deleteMessageTemplate,
  searchUsers
} from '@/api/message'

// 搜索表单
const searchForm = reactive({
  type: '',
  status: '',
  dateRange: []
})

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 消息列表数据
const loading = ref(false)
const messageList = ref([])
const selectedMessages = ref([])

// 发送消息相关
const sendDialogVisible = ref(false)
const sendFormRef = ref(null)
const sendForm = reactive({
  type: '',
  title: '',
  content: '',
  receivers: [],
  methods: ['system'],
  sendTimeType: 'now',
  scheduleTime: null
})

// 发送消息表单验证规则
const sendRules = {
  type: [
    { required: true, message: '请选择消息类型', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入消息标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' }
  ],
  receivers: [
    { required: true, message: '请选择接收人', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一个接收人', trigger: 'change' }
  ],
  methods: [
    { required: true, message: '请选择发送方式', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一种发送方式', trigger: 'change' }
  ],
  scheduleTime: [
    { required: true, message: '请选择发送时间', trigger: 'change' }
  ]
}

// 用户搜索相关
const userSearchLoading = ref(false)
const userOptions = ref([])

// 消息模板相关
const templateDialogVisible = ref(false)
const templateList = ref([])

// 查看消息相关
const viewDialogVisible = ref(false)
const currentMessage = ref({})

// 获取消息列表
const getMessageListData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      page: page.current,
      size: page.size
    }
    const { data } = await getMessageList(params)
    messageList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取消息列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取消息模板列表
const getTemplateListData = async () => {
  try {
    const { data } = await getMessageTemplateList()
    templateList.value = data
  } catch (error) {
    console.error('获取消息模板列表失败:', error)
  }
}

// 搜索用户
const handleSearchUsers = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      const { data } = await searchUsers({ keyword: query })
      userOptions.value = data
    } catch (error) {
      console.error('搜索用户失败:', error)
    } finally {
      userSearchLoading.value = false
    }
  } else {
    userOptions.value = []
  }
}

// 获取消息类型标签
const getMessageTypeTag = (type) => {
  const typeMap = {
    system: '',
    business: 'success',
    activity: 'warning',
    security: 'danger'
  }
  return typeMap[type] || ''
}

// 获取消息类型标签文本
const getMessageTypeLabel = (type) => {
  const typeMap = {
    system: '系统通知',
    business: '业务通知',
    activity: '活动通知',
    security: '安全通知'
  }
  return typeMap[type] || type
}

// 获取消息状态标签
const getMessageStatusTag = (status) => {
  const statusMap = {
    unread: 'info',
    read: 'success',
    deleted: 'danger',
    failed: 'warning'
  }
  return statusMap[status] || ''
}

// 获取消息状态标签文本
const getMessageStatusLabel = (status) => {
  const statusMap = {
    unread: '未读',
    read: '已读',
    deleted: '已删除',
    failed: '发送失败'
  }
  return statusMap[status] || status
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getMessageListData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedMessages.value = selection
}

// 发送消息
const handleSend = () => {
  Object.keys(sendForm).forEach(key => {
    if (key === 'methods') {
      sendForm[key] = ['system']
    } else if (key === 'sendTimeType') {
      sendForm[key] = 'now'
    } else {
      sendForm[key] = ''
    }
  })
  sendDialogVisible.value = true
}

// 提交发送消息
const handleSendSubmit = async () => {
  if (!sendFormRef.value) return
  
  try {
    await sendFormRef.value.validate()
    const data = {
      ...sendForm,
      sendTime: sendForm.sendTimeType === 'schedule' ? sendForm.scheduleTime : null
    }
    await sendMessage(data)
    ElMessage.success('发送成功')
    sendDialogVisible.value = false
    getMessageListData()
  } catch (error) {
    console.error('发送消息失败:', error)
  }
}

// 重发消息
const handleResend = async (row) => {
  try {
    await ElMessageBox.confirm('确认重新发送该消息吗？', '提示', {
      type: 'warning'
    })
    await resendMessage(row.id)
    ElMessage.success('重发成功')
    getMessageListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重发消息失败:', error)
    }
  }
}

// 删除消息
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该消息吗？', '提示', {
      type: 'warning'
    })
    await deleteMessage(row.id)
    ElMessage.success('删除成功')
    getMessageListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除消息失败:', error)
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedMessages.value.length) return
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedMessages.value.length} 条消息吗？`, '提示', {
      type: 'warning'
    })
    const ids = selectedMessages.value.map(item => item.id)
    await batchDeleteMessages(ids)
    ElMessage.success('批量删除成功')
    getMessageListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除消息失败:', error)
    }
  }
}

// 查看消息
const handleView = (row) => {
  currentMessage.value = row
  viewDialogVisible.value = true
}

// 消息模板
const handleTemplate = () => {
  templateDialogVisible.value = true
  getTemplateListData()
}

// 新增模板
const handleAddTemplate = () => {
  // TODO: 实现新增模板功能
}

// 编辑模板
const handleEditTemplate = (row) => {
  // TODO: 实现编辑模板功能
}

// 删除模板
const handleDeleteTemplate = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该模板吗？', '提示', {
      type: 'warning'
    })
    await deleteMessageTemplate(row.id)
    ElMessage.success('删除成功')
    getTemplateListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除模板失败:', error)
    }
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getMessageListData()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getMessageListData()
}

onMounted(() => {
  getMessageListData()
})
</script>

<style lang="scss" scoped>
.message-manage {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .action-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.template-header {
  margin-bottom: 20px;
}

.message-detail {
  .message-header {
    margin-bottom: 20px;

    h3 {
      margin: 0 0 10px;
      font-size: 18px;
    }

    .message-meta {
      display: flex;
      align-items: center;
      gap: 15px;
      color: #909399;
      font-size: 14px;
    }
  }

  .message-content {
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 20px;
    white-space: pre-wrap;
  }

  .message-footer {
    .receiver-info {
      color: #909399;
      font-size: 14px;

      p {
        margin: 5px 0;
      }
    }
  }
}

.user-info {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}
</style> 